package com.spring.le.aspect;

import com.spring.le.model.Address;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

@Aspect
@Component
public class LogAspect {
    /**
     * *表示任意返回值
     * ..表示暴击子包下的内容
     * （..）方法里可以有任意多个参数
     */

    @Pointcut("@annotation(com.spring.le.anno.Save)")
    public void insert(){
        //连接点
    }

    @Before("insert()")
    public void before(JoinPoint joinPoint) throws IllegalAccessException, NoSuchFieldException {
        // 通过joinPoint可以拿到方法调用信息
        Address address=((Address)joinPoint.getArgs()[0]);
        System.out.println("====切面前置操作====");
        Class clazz=address.getClass();
        //设置日期
        long t=System.currentTimeMillis();
        Date date=new Date();
        date.setTime(t);
        //格式化
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time=sdf.format(date);

        Field creatBy=clazz.getDeclaredField("creatBy");
        Field creatTime=clazz.getDeclaredField("creatTime");
        creatBy.setAccessible(true);
        creatTime.setAccessible(true);
        creatBy.set(address,"name");
        creatTime.set(address,time);
    }
}
